package com.sky.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.user.mapper.UserMapper;
import com.sky.user.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
@ComponentScan(basePackages = "com.sky.properties")
public class UserServiceImpl implements UserService {

    // 微信服务接口地址
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserMapper userMapper;


    /**
     * 微信用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {
        log.info("code:"+userLoginDTO.getCode());
        String openid = getOpenId(userLoginDTO.getCode());
        log.info("openid:"+openid);
        // 登录失败
        if(openid == ""){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 如果是新用户则注册
        User user = userMapper.getByOpenId(openid);
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        // 为用户创建jwt令牌
        Map<String,Object> claim = new HashMap<>();
        claim.put(JwtClaimsConstant.USER_ID,user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claim);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(jwt)
                .build();
        return userLoginVO;
    }

    /**
     * 获取用户唯一标识openid
     * @param code
     * @return
     */
    private String getOpenId(String code){
        Map<String,String> params = new HashMap<>();
        params.put("appid",weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code",code);
        params.put("grant_type","authorization_code");

        String json = HttpClientUtil.doGet(WX_LOGIN, params);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }

}
